from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, \
    AddressSerializer, AddressTitleSerializer, UserBrowseHistorySerializer
from goods.serializers import SKUSerializer
from rest_framework_jwt.settings import api_settings
from datetime import datetime

from .models import User, Address
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis


# from meiduo_mall.apps.users.models import User

# Create your views here.
class UserView(CreateAPIView):
    """注册"""

    # 指定序列化器类
    serializer_class = CreateUserSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        response = Response(serializer.data, status=status.HTTP_201_CREATED)
        merge_cart_cookie_to_redis(request, user, response)
        return response

class UsernameCountView(APIView):
    """判断用户名是否已存在"""


    def get(self, request, username):
        # 用username去User模型中查询此用户名的数据
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        # 响应
        return Response(data)


class MobileCountView(APIView):
    """判断手机号是否已存在"""

    def get(self, request, mobile):
        # 用username去User模型中查询此用户名的数据
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        # 响应
        return Response(data)

# GET  /user/
class UserDetailView(RetrieveAPIView):
    """展示用户个人信息"""
    # 指定序列化器类
    serializer_class = UserDetailSerializer
    # 指定查询集?
    # queryset = User.objects.all()
    # def get_object(self):
    # instance = self.get_object()  Retrieve 扩展中此行代码由于路由中没有Pk所以此方法获取不到查询集中的单个模型对象
    # 指定视图的权限
    permission_classes = [IsAuthenticated]

    def get_object(self):
        # 重写获取单一模型对象的方法,手动从请求对象获取user 并返回
        return self.request.user


# PUT /email/
class EmailView(UpdateAPIView):
    """设置邮箱"""

    # 指定序列化器
    serializer_class = EmailSerializer

    # 指定视图的权限
    permission_classes = [IsAuthenticated]

    # 重写get_object方法返回user对象
    def get_object(self):
        return self.request.user


# GET //
class VerifyEmailView(APIView):
    """激活邮箱"""

    def get(self, request):
        # 1.获取前端传入查询参数
        token = request.query_params.get('token')
        # 1.1 如果token没有提取,响应
        if not token:
            return Response({'message': '没有token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 对获取到的token进行解密,并且查询user
        user = User.check_verify_email_token(token)
        # 3. 判断是否获取出user,如果没有响应
        if not user:
            return Response({'message': 'token无效'}, status=status.HTTP_400_BAD_REQUEST)
        # 4. 修改user对象的email_active字段为True
        user.email_active = True
        user.save()
        # 5.响应
        return Response({'message': 'ok'})











class AddressViewSet(UpdateModelMixin, CreateModelMixin, GenericViewSet):
    """用户收货地址增删改查"""
    
    # 指定序列化器
    serializer_class = AddressSerializer
    # 指定权限
    permission_classes = [IsAuthenticated]

    # 指定查询集
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    
    def create(self, request, *args, **kwargs):
        # 判断当前用户的收货地址数据,是否上限,如果上限直接响应
        count = request.user.addresses.count()
        # count = Address.objects.filter(user=request.user).count()
        if count >= 20:  # 判断地址上限,不能超过20个
            return Response({'message': '用户收货地址达到上限'}, status=status.HTTP_400_BAD_REQUEST)
        # # 创建序列化器进行反序列化
        # serializer = self.get_serializer(data=request.data, context={})
        # # 调用序列化器校验方法
        # serializer.is_valid(raise_exceptions=True)
        # # 调用序列化器的save()
        # serializer.save()
        # # 响应
        # return Response(serializer.data, status=status.HTTP_201_CREATED)
        return super(AddressViewSet, self).create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


class UserBrowseHistoryView(CreateAPIView):
    """保存用户浏览记录"""
    # 指定用户权限
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = UserBrowseHistorySerializer


    def get(self, request):
        """获取用户浏览记录"""
        # 1.创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 2.获取当前的请求用户
        user = request.user
        # 调用lrange() 获取当前用户的浏览记录
        sku_id_list_bytes = redis_conn.lrange('history_%s' % user.id, 0, -1)
        # 通过sku_id取出一个一个的sku模型
        # SKU.objects.filter(id__in=sku_id_list_bytes)
        sku_list = []  # 为了保存浏览商品的顺序只能自己遍历一个一个查和添加到列表
        for sku_id_bytes in sku_id_list_bytes:
            sku = SKU.objects.get(id=sku_id_bytes)
            sku_list.append(sku)
        # 把模型进行序列化  创建序列化器时 instance 参数可以传递 模型对象, 字典  (查询集/列表   many=True)
        serializer = SKUSerializer(sku_list, many=True)

        # 响应
        return Response(serializer.data)

jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义jwt登录视图"""
    def post(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            # 账号密码登录合并购物车
            merge_cart_cookie_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)




